// 云函数入口文件
const cloud = require('wx-server-sdk')
const schedule = require('node-schedule')
const Core = require('@alicloud/pop-core');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
const log = cloud.logger()
const db = cloud.database()
const _ = db.command
var client = new Core({
    accessKeyId: 'LTAI5tK6U5rfMvt7PTiu1fHS',
    accessKeySecret: 'oaKgqZ8wVYD4PsgM56enq0gWi7AeVe',
    // securityToken: '<your-sts-token>', // use STS Token
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
  });
  var params = {
    "SignName": "阿里云短信测试",
    "TemplateCode": "SMS_154950909",
    "PhoneNumbers": "18628525985",
    "TemplateParam": "{\"code\":\"1234\"}"
  }
  var requestOption = {
    method: 'POST',
    formatParams: false,
  };
  
// Define the function that sends the reminder message
 async function sendReminderMessage(activity) {
    log.info({execStart:activity})
    
    try {
      // Get the list of members of the activity
      // Loop through the members and send them a reminder message
      let phone = activity.phone
    //  client.request('SendSms', params, requestOption).then((result) => {
    //     console.log(JSON.stringify(result));

    //   }, (ex) => {
    //     log.error({"sendError":ex})
    //   })
    if(activity.isRepreatType==0){
        return false
    }
    else{

        let times=1
        if(activity.isRepreatType==2){
            times=7
        }
        if(activity.isRepreatType==3){
            times=30
        }
        log.info({msg:{
            activateDate:activity.activateDate,
            description:activity.description,
            isRepreatType:activity.isRepreatType,
            needRemind:activity.needRemind,
            _openid:activity._openid,
            phone:18628525985,
            schduleTime:activity.schduleTime,
            type:activity.type,
            tag:activity.tag,
            startTime: new Date(new Date(activity.startTime).getTime() + 24 * 60 * 60 * 1000*times),
            endTime: new Date(new Date(activity.endTime).getTime() + 24 * 60 * 60 * 1000*times).toString(),
        }})
        await cloud.callFunction({
            name:"userSchduleService",
            data:{
                "activateDate":activity.schduleTime,
                "description":activity.description,
                "isRepreatType":activity.isRepreatType,
                "needRemind":activity.needRemind,
                "_openid":activity._openid,
                "phone":18628525985,
                "type":activity.type,
                "startTime": new Date(new Date(activity.startTime).getTime() + 24 * 60 * 60 * 1000*times).toString(),
                "endTime": new Date(new Date(activity.endTime).getTime() + 24 * 60 * 60 * 1000*times).toString(),
                "tag":activity.tag
            }
        }).then((info)=>{
            log.info({info})
            return true
        }).catch((err)=>{
            log.info({err})
            return false
        })
    }
      
    } catch (err) {
      log.error({"exec":err})
      return false
    }
}
  
  // Define the function that schedules the task
   function scheduleReminderTask(activity) {
    try {
      const startTime = new Date(activity.startTime)
      const reminderTime = new Date(startTime.getTime() - 5 * 60 * 1000)
      log.info({task:`尝试添加定时任务${reminderTime.getTime()}`})
      const job = schedule.scheduleJob(reminderTime,()=>{
        sendReminderMessage(activity)
      })
      log.info({task:`taskResult:${job}`})
      return true
    } catch (err) {
        log.error({"exec":err})
         return false
    }
  }
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let g =await db.collection("schdule").where({
        needRemind:true,
        startTime:_.lte(new Date(new Date().getTime()+1000*60*5))
    }).get()
    console.log(g)
    if(!g.data) {
        return false
    }
    for(let i =0;i<=g.data.length;i++){
        sendReminderMessage(g.data[i])
    }
    db.collection("schdule").where({
        needRemind:true,
        startTime:_.lte(new Date(new Date().getTime()+1000*60*5))
    }).update({
        data:{
            needRemind:false,
            isDone:true
        },
        multi:true
    })
    return {
        "code":200,
        "msg":"success to create schedule task"
    }
}